<template>
  <div class="admin-user-edit">
    <a-card :title="isEdit ? '编辑管理员' : '创建管理员'" :bordered="false">
      <template #extra>
        <a-button @click="goBack">
          <left-outlined /> 返回
        </a-button>
      </template>
      
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="用户名" name="username">
          <a-input 
            v-model:value="formState.username" 
            placeholder="请输入用户名"
            :disabled="isEdit" 
          />
        </a-form-item>
        
        <a-form-item 
          label="密码" 
          name="password"
          :rules="isEdit ? [{ required: false }] : rules.password"
        >
          <a-input-password
            v-model:value="formState.password"
            placeholder="请输入密码"
          />
          <div v-if="isEdit" class="password-tip">不修改密码请留空</div>
        </a-form-item>
        
        <a-form-item label="姓名" name="name">
          <a-input v-model:value="formState.name" placeholder="请输入姓名" />
        </a-form-item>
        
        <a-form-item label="手机号" name="phone">
          <a-input v-model:value="formState.phone" placeholder="请输入手机号" />
        </a-form-item>
        
        <a-form-item label="状态" name="status">
          <a-radio-group v-model:value="formState.status">
            <a-radio :value="1">启用</a-radio>
            <a-radio :value="0">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
        
        <a-form-item :wrapper-col="{ offset: 4, span: 16 }">
          <a-button type="primary" @click="submitForm" :loading="loading">
            {{ isEdit ? '保存修改' : '立即创建' }}
          </a-button>
          <a-button style="margin-left: 10px" @click="resetForm">
            重置
          </a-button>
        </a-form-item>
      </a-form>
    </a-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import axios from 'axios';
import { LeftOutlined } from '@ant-design/icons-vue';

const route = useRoute();
const router = useRouter();
const formRef = ref();
const loading = ref(false);

// 判断是否是编辑模式
const isEdit = computed(() => {
  return route.params.id && route.params.id !== 'new';
});

// 表单数据
const formState = reactive({
  username: '',
  password: '',
  name: '',
  phone: '',
  status: 1
});

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 4, max: 20, message: '用户名长度应为4-20个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应为6-20个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
};

// 获取用户信息
const getUserInfo = async (id) => {
  try {
    loading.value = true;
    const res = await axios.get(`/admin/api/admin-users/${id}`);
    if (res.data.code === 0) {
      const userData = res.data.data;
      // 更新表单数据，但不包含密码
      formState.username = userData.username;
      formState.name = userData.name;
      formState.phone = userData.phone;
      formState.status = userData.status;
    } else {
      message.error(res.data.message || '获取用户信息失败');
    }
  } catch (error) {
    message.error('获取用户信息失败: ' + error.message);
  } finally {
    loading.value = false;
  }
};

// 提交表单
const submitForm = () => {
  formRef.value.validate().then(() => {
    if (isEdit.value) {
      updateUser();
    } else {
      createUser();
    }
  }).catch(error => {
    console.log('验证失败:', error);
  });
};

// 创建用户
const createUser = async () => {
  try {
    loading.value = true;
    const res = await axios.post('/admin/api/admin-users', formState);
    if (res.data.code === 0) {
      message.success('创建成功');
      router.push('/admin-users');
    } else {
      message.error(res.data.message || '创建失败');
    }
  } catch (error) {
    message.error('创建失败: ' + error.message);
  } finally {
    loading.value = false;
  }
};

// 更新用户
const updateUser = async () => {
  try {
    loading.value = true;
    // 编辑时如果密码为空，则不传递密码字段
    const data = { ...formState };
    if (!data.password) {
      delete data.password;
    }
    
    const res = await axios.put(`/admin/api/admin-users/${route.params.id}`, data);
    if (res.data.code === 0) {
      message.success('更新成功');
      router.push('/admin-users');
    } else {
      message.error(res.data.message || '更新失败');
    }
  } catch (error) {
    message.error('更新失败: ' + error.message);
  } finally {
    loading.value = false;
  }
};

// 重置表单
const resetForm = () => {
  if (isEdit.value) {
    getUserInfo(route.params.id);
  } else {
    formRef.value.resetFields();
  }
};

// 返回
const goBack = () => {
  router.push('/admin-users');
};

// 页面加载时，如果是编辑模式则获取用户信息
onMounted(() => {
  if (isEdit.value) {
    getUserInfo(route.params.id);
  }
});
</script>

<style scoped>
.admin-user-edit {
  padding: 24px;
}

.password-tip {
  color: #999;
  font-size: 12px;
  margin-top: 4px;
}
</style> 